<template>
  <div class="upload">
    <el-dialog
      custom-class="reset-dialog-box"
      width="400px"
      :visible.sync="visible"
      :before-close="handleConfirm"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="title"
    >
      <div class="upload-block">
        <div class="upload-title">选择文件</div>
        <el-upload
          ref="upload"
          class="upload-button"
          v-on:on-progress="handlePreview"
          :action="action"
          :data="uploadData"
          :multiple="multiple"
          :accept="fileAcceptList"
          :before-upload="handleBeforeUpload"
          :on-success="onSuccess"
          :on-error="onError"
          :on-change="handleChange"
          :show-file-list="false"
          :file-list="fileList"
          :auto-upload="false"
        >
          <!-- 
          :headers="headerObj"
         -->
          <el-input
            slot="trigger"
            v-model="fileName"
            size="small"
            class="filter-item"
            placeholder=""
          />
        </el-upload>
      </div>
      <div v-if="multiple && fileList.length" class="multiple-box">
        <div v-for="(item, index) in fileList" :key="item.name + item.uid">
          <span>{{ item.name }}</span>
          <i @click="onDelFile(index)" class="el-icon-delete"></i>
        </div>
      </div>
      <div class="btn-box">
        <!-- <el-button @click="downFile" size="small">下载模板</el-button> -->
        <el-button
          :loading="loading"
          :disabled="uploadBtnDisabled"
          type="primary"
          size="small"
          @click="submitUpload"
          >{{ buttonTxt }}</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  props: {
    visible: {
      type: Boolean,
      required: true,
    },
    buttonTxt: {
      type: String,
      default: "上传",
    },
    flag: {
      type: Boolean,
      default: false,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    action: {
      type: String,
      required: true,
    },
    isOnSubmit: {
      type: Boolean,
      required: false,
    },
    buttonType: {
      type: String,
      default: "primary",
    },
    downloadUrl: {
      type: String,
      default: "",
      required: false,
    },
    title: {
      type: String,
      default: "上传文件",
      required: false,
    },
    // image/*
    fileAcceptList: {
      type: String,
      default: "",
    },
    uploadData: {
      type: Object,
      default: () => {
        return {};
      },
      required: false,
    },
    fileSize: null, // 文件大小限制，单位为K
    uploadId: null,
    name: null,
    onProgress: Function,
    beforeUpload: Function,
    isOkClear: {
      // 导入成功是否清除fileList
      type: Boolean,
      default: false,
    },
    isOnce: {
      // 保持filelist只存在1个文件数据
      type: Boolean,
      default: false,
    },
    errorData: {
      // 接收失败数据传入
      type: String,
      default: "",
    },
  },
  data() {
    return {
      num: 0,
      fileList: [],
      fileName: "",
      loading: false,
      dialogVisible: false,
      // headerObj: {
      //   Authorization: getAuthorization()
      // },
      errorFileName: "",
    };
  },
  computed: {
    uploadBtnDisabled() {
      return this.fileList.length === 0;
    },
  },
  methods: {
    downFailFile() {
      this.downData(this.errorData);
    },
    downFile() {
      this.downData(this.downloadUrl);
    },
    downData(data) {
      if (data) {
        // window.location.href = this.downloadUrl;
        let fileName = "";
        try {
          const splitUrl = data.split("/");
          const url = splitUrl[splitUrl.length - 1];
          fileName = url.slice(0, url.lastIndexOf("."));
        } catch (error) {}
        exportFile("base64")({
          url: data,
          fileName,
          fileType: "xlsx",
        });
      }
    },
    handleChange(file, fileList) {
      if (fileList.length) {
        if (this.multiple) {
          this.fileName = "";
          this.fileList = fileList;
        } else {
          this.fileName = file.name;
          this.fileList =
            fileList.length === 1 ? fileList : [fileList[fileList.length - 1]];
          try {
            this.$emit("uploadOnchange", {
              diskUrl:
                document.getElementsByClassName("el-upload__input")[0].value,
            });
          } catch (error) {}
        }
      } else {
        this.fileName = "";
        this.fileList = [];
      }
    },
    handleConfirm() {
      this.$emit("onHide");
      this.$emit("update:visible", false);
    },
    importShow() {
      this.dialogVisible = true;
    },
    handleBeforeUpload(file) {
      // const fileName = file.name;
      // const ext = fileName
      //   .substring(fileName.lastIndexOf(".") + 1)
      //   .toLowerCase();
      // if (this.fileAcceptList) {
      //   // 限制文件格式
      //   if (this.fileAcceptList.indexOf(ext) < 0) {
      //     this.$message.error("文件类型不合法，请上传" + this.fileAcceptList);
      //     return false;
      //   }
      // }
      // if (this.fileSize) {
      //   // 限制文件大小，单位为k
      //   if (file.size / 1024 > this.fileSize) {
      //     this.$message.error("文件大小限制为" + this.fileSize + "k");
      //     return false;
      //   }
      // }
      this.loading = true; // 开启上传中状态
      // if (this.beforeUpload) {
      //   const arg = [].slice.call(arguments);
      //   if (this.uploadId) {
      //     arg.push(this.uploadId);
      //   }
      //   this.beforeUpload.apply(this, arg);
      // }
    },
    onDelFile(index) {
      this.fileList.splice(index, 1);
    },
    handlePreview() {
      this.$emit("on-progress");
    },
    onSuccess(res, file) {
      const { result, code, message, data } = res;
      // if (result == 0 || code == 0) {
      //   this.dialogVisible = false;
      if (this.multiple) {
        this.num = this.num + 1;
        if (this.num === this.fileList.length) {
          this.loading = false; // 关闭上传中状态

          this.$emit("uploadSuccess", {
            status: "ok",
            data: res,
          });
        }
      } else {
        this.loading = false; // 关闭上传中状态

        this.$emit("uploadSuccess", {
          status: "ok",
          data: res,
        });
      }
      //   this.$refs.upload.clearFiles();
      // } else {
      //   this.$refs.upload.clearFiles();
      //   this.$message({
      //     message,
      //     type: "error",
      //   });
      // }
    },
    onError(error) {
      // 关闭上传中状态
      this.loading = false;
      this.$message.error("上传失败");
      if (this.multiple) {
        this.num = this.num + 1;
      }
      if (this.isOkClear) this.$refs.upload.clearFiles();
    },
    submitUpload() {
      if (this.uploadBtnDisabled) {
        this.$message.warning("文件不能为空哦~");
      }
      if (this.isOnSubmit) {
        this.$emit("onSubmit");
        return;
      }
      this.$refs.upload.submit();
    },
  },
};
</script>
<style lang="scss" scoped>
.multiple-box {
  padding-top: 8px;
  > div {
    margin-bottom: 4px;
    > span {
      margin-right: 10px;
    }
    > i {
      cursor: pointer;
    }
  }
}
.btn-box {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
  .download-block {
    height: 28px;
    line-height: 28px;
    text-align: center;
    border: 1px solid #d7dce4;
    margin-right: 16px;
    border-radius: 2px;
    color: #333333;
    font-size: 12px;
    padding: 0 15px;
  }
  .el-button--small {
    // width: 60px;
    height: 28px;
    border-radius: 2px;
    padding: 0px 15px;
  }
}
.errorFile {
  margin-top: 16px;
  font-size: 12px;
  font-weight: 400;
  font-family: PingFang, PingFang-Regular;
  img {
    margin-right: 3px;
    position: relative;
    top: 3px;
  }
  .errorFile-info {
    width: 100%;
    height: 27px;
    background: rgba(232, 99, 99, 0.08);
    border-radius: 2px;
    padding-left: 7px;
    > span {
      position: relative;
      top: 5px;
      color: #e86363;
    }
  }
  .errorFile-button {
    text-align: right;
    button {
      border: none;
      color: #3f99a3;
    }
  }
}
.upload-block {
  display: flex;
  align-items: center;
  .upload-title {
    margin-right: 4px;
  }
  ::v-deep.upload-button {
    flex: 1;
    div {
      width: 100% !important;
    }
    .el-input__inner {
      cursor: pointer;
    }
  }
  span {
    height: 40px;
    line-height: 40px;
    width: 30px;
  }
}
.import-butt {
  width: 100px;
  opacity: 1;
  border: 1px solid #3f99a3;
  border-radius: 5px;
}
.el-input--small {
  width: 220px;
  margin-left: 4px;
}
::v-deep .el-dialog__body {
  padding: 20px !important;
}
::v-deep.el-dialog__headerbtn {
  margin-top: 0px;
}
</style>
